package com.yiwyn.demo.servicer;

import com.yiwyn.demo.domain.User;
import com.yiwyn.demo.event.MyTransactionEvent;
import com.yiwyn.demo.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.lang.NonNullApi;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.*;

import java.util.UnknownFormatConversionException;

@Slf4j
@Service
public class TestService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private PlatformTransactionManager transactionManager;

    @Autowired
    private TransactionTemplate transactionTemplate;

    @Autowired
    private ApplicationEventPublisher applicationEventPublisher;

    @Autowired
    private TService tService;

    @Transactional(rollbackFor = Exception.class)
    public String test() {
        return demo3();
    }

    public String demo1() {

        DefaultTransactionDefinition def = new DefaultTransactionDefinition();
        def.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED);
        def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);

        // 开始事务
        TransactionStatus status = transactionManager.getTransaction(def);

        // 需要在事务前配置事务钩子
        if (TransactionSynchronizationManager.isSynchronizationActive()) {
            TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
                @Override
                public void afterCompletion(int status) {
                    try {
                        String name = TransactionSynchronizationManager.getCurrentTransactionName();
                        System.out.println("当前事务名：" + name);
                        String a = null;
                        System.out.println("事务状态：" + status);
                    } catch (Exception e) {
                        log.error("钩子函数执行异常:", e);
                    }
                }
            });
        }

        try {
            User u = new User();
            u.setId(1);
            u.setUsername("测试");
            userMapper.insert(u);
            Integer id = u.getId();

            transactionManager.commit(status);
        } catch (Exception e) {
            // 异常时回滚事务
            transactionManager.rollback(status);
            throw e; // 继续抛出异常
        }
        return "success";
    }

    public String demo2() {
        transactionTemplate.execute(new TransactionCallback<Object>() {
            @Override
            public Object doInTransaction(TransactionStatus status) {

                // 需要在事务前配置事务钩子
                if (TransactionSynchronizationManager.isSynchronizationActive()) {
                    TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
                        @Override
                        public void afterCompletion(int status) {
                            try {
                                String name = TransactionSynchronizationManager.getCurrentTransactionName();
                                System.out.println("当前事务名：" + name);
                                String a = null;
                                System.out.println("事务状态：" + status);
                            } catch (Exception e) {
                                log.error("钩子函数执行异常:", e);
                            }
                        }
                    });
                }

                try {
                    User u = new User();
                    u.setId(1);
                    u.setUsername("测试");
                    userMapper.insert(u);
                    Integer id = u.getId();

                    transactionManager.commit(status);
                } catch (Exception e) {
                    // 异常时回滚事务
                    transactionManager.rollback(status);
                    throw e; // 继续抛出异常
                }
                return null;
            }
        });
        return "success";
    }


    public String demo3() {

//
//        // 需要在事务前配置事务钩子
//        if (TransactionSynchronizationManager.isSynchronizationActive()) {
//            TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
//                @Override
//                public void afterCompletion(int status) {
//                    try {
//                        log.info("事务执行状态:{}", status);
//                        if (status == TransactionSynchronization.STATUS_COMMITTED) {
//                            tService.beforeUpdate();
//                        }
//                    } catch (Exception e) {
//                        log.error("钩子函数执行异常:", e);
//                    }
//                }
//            });
//        }



        // 需要在事务前配置事务钩子
        if (TransactionSynchronizationManager.isSynchronizationActive()) {
            TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
                @Override
                public void afterCompletion(int status) {
                    try {
                        log.info("事务执行状态:{}", status);
                        if (status == TransactionSynchronization.STATUS_COMMITTED) {
                            tService.afterUpdate();
                        }
                    } catch (Exception e) {
                        log.error("钩子函数执行异常:", e);
                    }
                }
            });
        }

        try {
            User u = new User();
            u.setId(1);
            u.setUsername("测试");
            userMapper.insert(u);
            Integer id = u.getId();
        } catch (Exception e) {
            throw new RuntimeException(e); // 继续抛出异常
        }
        log.info("test方法执行完成");
        return "success";
    }

    public String demo4Listener() {
        // 需要在事务前配置事务钩子
        applicationEventPublisher.publishEvent(new MyTransactionEvent(this, "demo4操作事务"));
        try {
            User u = new User();
            u.setId(1);
            u.setUsername("测试");
            userMapper.insert(u);
            Integer id = u.getId();
        } catch (Exception e) {
            throw new RuntimeException(e); // 继续抛出异常
        }

        return "success";
    }
}
